#include "../include/server.h"
int main(int argc, char *argv[])
{
    ARGS_CHECK(argc, 4);
    pipe(exit_pipe);
    pid_t pid = fork();
    if (pid > 0) //父进程
    {
        printf("father id is %d\n", getpid());
        close(exit_pipe[0]);
        signal(SIGUSR1, sig_func);
        wait(NULL);
        exit(0);
    }
    close(exit_pipe[1]);
    int sfd = init_socket(argv[1], argv[2]);
    MYSQL *scon = init_mysql();
    if (scon == NULL)
    {
        return 0;
    }

    Thread_Pool thread_pool;
    init_thread_pool(&thread_pool, argv[3]);
    create_thread(&thread_pool, thread_pool.pthread_num);
    int ret;
    Train train;

    int efd = epoll_create(1);
    ERROR_CHECK(efd, -1, "epoll_create");
    add_epoll(efd, sfd);
    add_epoll(efd, exit_pipe[0]);
    struct epoll_event evs[2];
    while (1)
    {
        int readynum = epoll_wait(efd, evs, 2, -1);
        for (int i = 0; i < readynum; i++)
        {
            if (evs[i].data.fd == sfd)
            {
                Login_Usr login_usr;
                int newfd = accept(sfd, NULL, NULL), usr_id;
                if (client_login(scon, newfd, &usr_id) == F_ret)
                {
                    close(newfd);
                    continue;
                }
                else
                {
                    login_usr.usr_id = usr_id;
                    login_usr.sfd = newfd;
                    select_dir_id(scon, &login_usr);
                    printf("usr_first_dir_id=%d\n", login_usr.dir_id);
                    printf("login success\n");
                }
                ret = pthread_mutex_lock(&thread_pool.tqueue.mutex);
                PTHREAD_ERROR_CHECK(ret, "pthread_mutex_lock");
                add_queue(&thread_pool.tqueue, &login_usr, scon);
                printf("main login_usr.sfd=%d\n", login_usr.sfd);
                ret = pthread_cond_signal(&thread_pool.tqueue.cond);
                PTHREAD_ERROR_CHECK(ret, "pthread_cond_signal");
                ret = pthread_mutex_unlock(&thread_pool.tqueue.mutex);
                PTHREAD_ERROR_CHECK(ret, "pthread_mutex_unlock");
            }
            else
            {
                int tmp;
                read(evs[i].data.fd, &tmp, sizeof(tmp));
                printf("son receive exit flag=%d\n", tmp);
                thread_pool.exit_flag = 1;
                pthread_cond_broadcast(&thread_pool.tqueue.cond);
                for (int i = 0; i < thread_pool.pthread_num; i++)
                {
                    pthread_join(thread_pool.ptid[i], NULL);
                }
                destroy_thread_pool(&thread_pool);
                close(sfd);
                exit(0);
            }
        }
    }
    close(sfd);
    mysql_close(scon);
    return 0;
}